package com.siblings.loan.analysis.http

import com.siblings.loan.analysis.AnalysisBuilder
import com.siblings.loan.analysis.aes.AnalysisAesUtil
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

object UrlHelper {

    fun combineUrl(): String {
        if (AnalysisBuilder.host.isBlank() or
            AnalysisBuilder.zone.isBlank() or
            AnalysisBuilder.pathCommon.isBlank()
        ) {
            return ""
        }

        val zone = AnalysisBuilder.zone
        AnalysisBuilder.zone = zone.replace("/", "")

        val pathCommon = AnalysisBuilder.pathCommon
        AnalysisBuilder.pathCommon = if (pathCommon.startsWith("/")) {
            pathCommon.replace("/", "")
        } else {
            pathCommon
        }

        return AnalysisBuilder.host + "/" + AnalysisBuilder.zone + "/" + AnalysisBuilder.pathCommon
    }
}

object HttpHelper {

    private var _poolExecutor: ThreadPoolExecutor? = null

    private fun poolExecutor(): ThreadPoolExecutor {
        if (_poolExecutor == null) {
            val availableCoreSize = Runtime.getRuntime().availableProcessors() / 2
            val corePoolSize = if (availableCoreSize > 0) availableCoreSize else 1
            val keepAliveTime = 60.toLong()
            val workQueue: BlockingQueue<Runnable> = LinkedBlockingDeque()

            _poolExecutor = ThreadPoolExecutor(
                corePoolSize,
                corePoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue
            ).apply {
                allowCoreThreadTimeOut(true)
            }
        }

        return _poolExecutor!!
    }

    fun postData(toUrl: String, body: String) {
        if (toUrl.isBlank()) return
        if (body.isBlank()) return

        poolExecutor().execute {
            try {
                println("toUrl:$toUrl")
                println("body:$body")
                println("body aes:${AnalysisAesUtil.decryptDefault(body)}")

                httpURLConnection(toUrl).apply {
                    outputStream.write(body.toByteArray())
                    outputStream.flush()
                    outputStream.close()

                    val isSuccess = (responseCode == HttpURLConnection.HTTP_OK)
                    if (isSuccess) {
                        println("${responseCode}--${toUrl}--post success!")
                    } else {
                        println("${responseCode}--${toUrl}--post fail!")
                    }
                    disconnect()
                }
            } catch (e: Exception) {
                e.printStackTrace();
                println("post fail! ${e.localizedMessage}")
            }
        }
    }

    @Throws(IOException::class)
    private fun httpURLConnection(toUrl: String): HttpURLConnection {
        val url = URL(toUrl)
        val urlConnection = url.openConnection() as HttpURLConnection
        urlConnection.setDoInput(true)
        urlConnection.setDoOutput(true)
        urlConnection.setUseCaches(false)
        urlConnection.setReadTimeout(180000)
        urlConnection.setConnectTimeout(120000)
        urlConnection.setRequestMethod("POST")
        urlConnection.setRequestProperty("Charset", "UTF-8")
        urlConnection.setRequestProperty("Connection", "Keep-Alive")
        urlConnection.setRequestProperty("Content-Type", "text/plain")
        urlConnection.setRequestProperty("Accept", "*/*")
        urlConnection.setRequestProperty("product", AnalysisBuilder.product)
        urlConnection.setRequestProperty("appid", AnalysisBuilder.product)
        return urlConnection
    }
}


